import React, { useReducer } from 'react';
import Item1 from './Item1';
import Item2 from './Item2';

// 初始默认值
const defaultState = { num: 0 };

// 对state值进行修改
const reducer = (prevState, action) => {
    let newState = { ...prevState };
    let { type, payload } = action;
    payload = payload ? payload : 1;
    switch (type) {
        case "DECREMENT":
            newState.num > 0 ? newState.num -= payload : 0;
            break;
        case "INCREMENT":
            newState.num += payload;
            break;
        default:
            break;
    }
    return newState;
};

// 初始默认值处理
const initAction = () => {
    return { ...defaultState }
}

function Box() {
    const [state, dispatch] = useReducer(reducer, defaultState, initAction);
    // 触发
    const increment = () => {
        dispatch({ type: "INCREMENT", payload: 1 });
    }
    const decrement = () => {
        dispatch({ type: "DECREMENT", payload: 1 });
    }
    return (
        <div className='wrapper wrapper1'>
            <h2 className='display-4'>useReducer基本使用</h2>
            <button onClick={increment} className='btn btn-danger'>父组件增加</button>
            <button onClick={decrement} className='ml-3 btn btn-warning'>父组件减少</button>
            <Item1 {...state} dispatch={dispatch} />
            <Item2 {...state} dispatch={dispatch} />
        </div>
    )
}

export default Box;